import cv2
import numpy as np
import random
import time

#游戏效果初步实现 使用按键控制

# 游戏参数
width, height = 800, 600  # 地图范围
snake_size = 10  # 减小蛇身和食物的大小
fps = 5  # 降低移动速度

# 初始化游戏状态
snake = [(100, 100), (90, 100), (80, 100)]  # 初始蛇身位置
direction = 'RIGHT'
food = (random.randint(0, width // snake_size - 1) * snake_size,
        random.randint(0, height // snake_size - 1) * snake_size)

def draw_snake_and_food(frame):
    # 绘制蛇的身体
    for i, (x, y) in enumerate(snake):
        color = (0, 255, 0) if i > 0 else (255, 0, 0)  # 蛇的身体用绿色，头部用蓝色
        cv2.rectangle(frame, (x, y), (x + snake_size, y + snake_size), color, -1)
    
    # 绘制食物
    cv2.rectangle(frame, (food[0], food[1]), (food[0] + snake_size, food[1] + snake_size), (0, 0, 255), -1)

def move_snake():
    global direction, food
    head_x, head_y = snake[0]
    if direction == 'UP':
        head_y -= snake_size
    elif direction == 'DOWN':
        head_y += snake_size
    elif direction == 'LEFT':
        head_x -= snake_size
    elif direction == 'RIGHT':
        head_x += snake_size

    new_head = (head_x, head_y)
    if new_head == food:
        snake.insert(0, new_head)
        food = (random.randint(0, width // snake_size - 1) * snake_size,
                random.randint(0, height // snake_size - 1) * snake_size)
    else:
        snake.insert(0, new_head)
        snake.pop()

def check_collision():
    head_x, head_y = snake[0]
    if head_x < 0 or head_x >= width or head_y < 0 or head_y >= height or (head_x, head_y) in snake[1:]:
        return True
    return False

def show_message(message, font_scale=1, thickness=3, wait_key=True):
    frame = np.zeros((height, width, 3), dtype=np.uint8)
    text_size = cv2.getTextSize(message, cv2.FONT_HERSHEY_SIMPLEX, font_scale, thickness)[0]
    text_x = (width - text_size[0]) // 2
    text_y = (height + text_size[1]) // 2
    cv2.putText(frame, message, (text_x, text_y), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), thickness)
    cv2.imshow('Snake Game', frame)
    if wait_key:
        cv2.waitKey(0)

# 显示“按任意键开始”
show_message("Press any key to start the game...", font_scale=0.8, thickness=2)

# 主循环
game_over = False
while not game_over:
    # 创建空白画布
    frame = np.zeros((height, width, 3), dtype=np.uint8)

    # 绘制蛇和食物
    draw_snake_and_food(frame)

    # 检测碰撞
    if check_collision():
        game_over = True
        show_message("Game Over! Press any key to exit...", font_scale=0.8, thickness=2, wait_key=True)
        break

    # 移动蛇
    move_snake()

    # 显示目标点的坐标和当前的蛇身长度
    food_text = f"Food: ({food[0]}, {food[1]})"
    length_text = f"Length: {len(snake)}"
    cv2.putText(frame, food_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
    cv2.putText(frame, length_text, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)

    # 显示帧
    cv2.imshow('Snake Game', frame)

    # 处理键盘输入
    key = cv2.waitKey(int(1000 / fps)) & 0xFF
    if key == ord('q'):
        break
    elif key == ord('w') and direction != 'DOWN':  # W键向上
        direction = 'UP'
    elif key == ord('s') and direction != 'UP':  # S键向下
        direction = 'DOWN'
    elif key == ord('a') and direction != 'RIGHT':  # A键向左
        direction = 'LEFT'
    elif key == ord('d') and direction != 'LEFT':  # D键向右
        direction = 'RIGHT'

# 等待按键释放所有窗口
cv2.waitKey(0)
cv2.destroyAllWindows()